package com.jy.api.controller.pos;

import com.jy.api.bean.Message;
import com.jy.api.bean.Response;
import com.jy.api.dao.NoticeDao;
import com.jy.api.dao.OrderDao;
import com.jy.api.domain.Notice;
import com.jy.api.util.Contens;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;

/**
 * Created by lihu on 2018/1/26.
 */
@Slf4j
@Controller
public class GreetingController {


    @Autowired
    OrderDao orderDao;


    @Autowired
    NoticeDao noticeDao;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 获取呼叫信息
     *
     * @param message
     * @param roomId
     * @throws Exception
     */
    @MessageMapping("/notice/{roomId}")
    public void greetingNotic(Message message, @DestinationVariable String roomId) throws Exception {

        String dest = "/notice-message/" + roomId + "/" + message.getStoreId();
        log.debug("message:{}", message);
        String time = stringRedisTemplate.opsForValue().get(Contens.SYNCH_NOTIC_TIME.
                replace("STOREID", message.getStoreId()));
        Response response = new Response();
        if (StringUtils.isBlank(time) || Long.parseLong(time) < message.getLastTimestamp().getTime()) {
            response.setLastTimestamp(message.getLastTimestamp());
        } else {
            List<Notice> notices = noticeDao.findByAddTimeAfterAndStoreIdAndStatesOrderByAddTimeAsc(
                    message.getLastTimestamp(),
                    message.getStoreId(), false);
            if (notices.size() > 0) {
                for (Notice notice : notices) {
                    notice.setStates(true);
                    response.getTableNo().add(notice.getTableNo());
                }
                noticeDao.save(notices);
                response.setCount(1);
                response.setLastTimestamp(new Date());
            } else {
                response.setLastTimestamp(new Date(new Date().getTime() - 1000));
            }

        }
        log.debug("response:{}", response);
        this.simpMessagingTemplate.convertAndSend(dest, response);

    }


    /**
     * 获取待办订单更新数量
     *
     * @param message
     * @return
     */
    @MessageMapping("/todo-orders/updates-count/{roomId}")
    public void greeting(Message message, @DestinationVariable String roomId) throws Exception {
        String dest = "/message/" + roomId + "/" + message.getStoreId();
        log.debug("message:{}", message);
        String time = stringRedisTemplate.opsForValue().get(Contens.SYNCH_ORDER_TIME.
                replace("STOREID", message.getStoreId()));
        Response response = new Response();
        if (message.getLastTimestamp() == null) {
            // 可能是第一次访问
            response.setLastTimestamp(new Date());
        } else if (StringUtils.isBlank(time) || Long.parseLong(time) < message.getLastTimestamp().getTime()) {
            // 没有新订单，更新时间
            response.setLastTimestamp(message.getLastTimestamp());
        } else {
            // 有新订单
            Long timeNumber = Long.parseLong(time);
            Date selectTiem = new Date(timeNumber - 1000);
            //如果查询时间大于3天 则直接更新轮询时间（前端不提示）
            if (new Date().getTime() - timeNumber > 10800000) {
                response.setLastTimestamp(new Date(new Date().getTime() - 1000));
            } else {
                Object count = orderDao.getCount(message.getStoreId(), selectTiem);
                int countInt = Integer.parseInt(count.toString());
                if (countInt > 0) {
                    response.setCount(1);
                    response.setLastTimestamp(new Date());
                } else {
                    response.setLastTimestamp(new Date(new Date().getTime() - 1000));
                }
            }
        }
        log.debug("response:{}", response);
        this.simpMessagingTemplate.convertAndSend(dest, response);
    }
}
